﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;

namespace cmsservice.BLL
{
    public class CompanyIPOBLL
    {
        DAL.CompanyIPODAL dal = new DAL.CompanyIPODAL();
        /// <summary>
        /// 缓存中获取新股数据(每小时更新一次)
        /// </summary>
        /// <returns></returns>
        public DataSet GetXGList()
        {
            DataSet ds = dal.GetXGList();
            return ds;
        }

        /// <summary>
        /// 从txt中读取新股数据
        /// </summary>
        /// <returns></returns>
        public List<Entity.CompanyIPOModel> GetModeListByTXT(string _path)
        {
            List<Entity.CompanyIPOModel> list = new List<Entity.CompanyIPOModel>();
            if (File.Exists(_path))
            {
                FileStream fs = File.Open(_path, FileMode.Open);
                StreamReader reader = new StreamReader(fs, Encoding.Default);
                string str = reader.ReadLine();
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Entity.CompanyIPOModel>>(str);
                reader.Close();
                fs.Close();
                fs.Dispose();
            }
            else
            {
                list = GetModelList();
                DateTime sdt = DateTime.Parse("2009-6-20");
                list = list.Where(a => a.OLIssueDate > sdt).OrderByDescending(a => a.OLIssueDate).ThenByDescending(a => a.OLApplyCode).ToList<Entity.CompanyIPOModel>();
                string str = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                using (StreamWriter sw = new StreamWriter(_path, false, Encoding.Default))
                {
                    sw.Write(str);
                    sw.Close();
                }
            }
            return list;
        }

        /// <summary>
        /// 从缓存中获取生成的新股详细信息
        /// </summary>
        /// <param name="xg"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        private List<Entity.CompanyIPOModel> GetModelList()
        {
            List<Entity.CompanyIPOModel> list = new List<Entity.CompanyIPOModel>();
            DataSet ds = GetXGList();
            DataTable dtCOMPANYIPO = ds.Tables[0];
            DataTable dtSECURITY = ds.Tables[1];
            DataTable dtBLOCKSTOCK = ds.Tables[2];
            DataTable dtSDDAILY = ds.Tables[3];
            foreach (DataRow dr in dtCOMPANYIPO.Rows)
            {
                Entity.CompanyIPOModel model = new Entity.CompanyIPOModel();
                model.OrgID = dr["OrgID"].ToString();
                model.OLApplyCode = dr["OLApplyCode"].ToString();
                DataRow[] drs = dtSECURITY.Select("SecuID='" + model.OrgID + "'");
                if (drs.Count() > 0)
                {
                    if (drs[0]["JJdate"] != null && drs[0]["JJdate"].ToString() != "")
                        model.JJdate = Convert.ToDateTime(drs[0]["JJdate"]);//网下申购解禁日
                    model.SecuCode = drs[0]["SecuCode"].ToString();
                    model.SecuAbbr = drs[0]["SecuAbbr"].ToString();
                    model.SecuMarket = drs[0]["SecuMarket"].ToString();//上市地点
                    if (drs[0]["ListedDate"] != null && drs[0]["ListedDate"].ToString() != "")
                        model.ListedDate = Convert.ToDateTime(drs[0]["ListedDate"]);//上市日期
                    if (drs[0]["ClosePrice"] != null && drs[0]["ClosePrice"].ToString() != "")
                        model.ClosePrice = Convert.ToDecimal(drs[0]["ClosePrice"]);//首日收盘价（元）
                    if (drs[0]["OpenPrice"] != null && drs[0]["OpenPrice"].ToString() != "")
                        model.OpenPrice = Convert.ToDecimal(drs[0]["OpenPrice"]);//首日开盘价（元）
                    if (drs[0]["ChangeRatio"] != null && drs[0]["ChangeRatio"].ToString() != "")
                        model.ChangeRatio = Convert.ToDecimal(drs[0]["ChangeRatio"]);//首日涨幅（%）
                    if (drs[0]["TurnoverRate"] != null && drs[0]["TurnoverRate"].ToString() != "")
                        model.TurnoverRate = Convert.ToDecimal(drs[0]["TurnoverRate"]);//首日换手率（%）

                    DataRow[] drbs = dtBLOCKSTOCK.Select("SecuCode='" + model.SecuCode + "'");
                    foreach (DataRow drb in drbs)
                    {
                        model.BlockName = drb["BlockName"].ToString();//所属行业
                        model.BlockCode = drb["BlockCode"].ToString();//所属行业代码
                    }

                    DataRow[] drsd = dtSDDAILY.Select("SecuCode='" + model.SecuCode + "'");
                    model.SecuCategory = "深市";
                    foreach (DataRow drd in drsd)
                    {
                        if (drd["SecuCategory"] != null && (drd["SecuCategory"].ToString() == "3001" || drd["SecuCategory"].ToString() == "3002"))
                        {
                            model.SecuCategory = "沪市";
                        }
                    }
                }
                else
                {
                    continue;
                }
                if (dr["TotalIssueVol"] != null && dr["TotalIssueVol"].ToString() != "")
                    model.TotalIssueVol = Convert.ToDecimal(dr["TotalIssueVol"]) * 10000;//发行总数（股）
                if (dr["OLApplyMoney"] != null && dr["OLApplyMoney"].ToString() != "")
                    model.OLApplyMoney = Convert.ToDecimal(dr["OLApplyMoney"]);//同上有效申购金
                if (dr["OLIssueVol"] != null && dr["OLIssueVol"].ToString() != "")
                    model.OLIssueVol = Convert.ToDecimal(dr["OLIssueVol"]) * 10000;//网上发行（股）
                if (dr["OLApplyMax"] != null && dr["OLApplyMax"].ToString() != "")
                    model.OLApplyMax = Convert.ToDecimal(dr["OLApplyMax"]) * 10000;//申购上限（股）
                if (dr["IssuePriceRMB"] != null && dr["IssuePriceRMB"].ToString() != "")
                    model.IssuePriceRMB = Convert.ToDecimal(dr["IssuePriceRMB"]);//发行价格（元/股）
                if (dr["OLIssueDate"] != null && dr["OLIssueDate"].ToString() != "")
                    model.OLIssueDate = Convert.ToDateTime(dr["OLIssueDate"]);//申购日期/上网发行日期
                if (dr["LotResultPublDate"] != null && dr["LotResultPublDate"].ToString() != "")
                    model.LotResultPublDate = Convert.ToDateTime(dr["LotResultPublDate"]);//中签号公布日/摇号结果公告日
                if (dr["OLLotRate"] != null && dr["OLLotRate"].ToString() != "")
                    model.OLLotRate = Convert.ToDecimal(dr["OLLotRate"]);//中签率(%)
                if (dr["OffLApplyMoney"] != null && dr["OffLApplyMoney"].ToString() != "")
                    model.OffLApplyMoney = Convert.ToDecimal(dr["OffLApplyMoney"]);//网下有效申购资金
                if (dr["DilutedPE"] != null && dr["DilutedPE"].ToString() != "")
                    model.DilutedPE = Convert.ToDecimal(dr["DilutedPE"]);//发行市盈率
                if (dr["OrgIntro"] != null)
                    model.OrgIntro = dr["OrgIntro"].ToString();//公司简介
                if (dr["BusinessMajor"] != null)
                    model.BusinessMajor = dr["BusinessMajor"].ToString();//主营业务
                if (dr["ParValue"] != null && dr["ParValue"].ToString() != "")
                    model.ParValue = Convert.ToDecimal(dr["ParValue"]);//发行面值（元）
                if (dr["ActualProceeds"] != null && dr["ActualProceeds"].ToString() != "")
                    model.ActualProceeds = Convert.ToDecimal(dr["ActualProceeds"]);//实际募集资金总额（亿元）
                if (dr["OffLApplyMoney"] != null && dr["OffLApplyMoney"].ToString() != "")
                    model.OffLApplyMoney = Convert.ToDecimal(dr["OffLApplyMoney"]);//网下有效申购资金
                if (dr["OffLLotRate"] != null && dr["OffLLotRate"].ToString() != "")
                    model.OffLLotRate = Convert.ToDecimal(dr["OffLLotRate"]);//网下配售中签率
                if (dr["OffLAllotVol"] != null && dr["OffLAllotVol"].ToString() != "")
                    model.OffLAllotVol = Convert.ToDecimal(dr["OffLAllotVol"]) * 10000;//网下配售股数（股）
                if (dr["OffLAllotEndDate"] != null && dr["OffLAllotEndDate"].ToString() != "")
                    model.OffLAllotEndDate = Convert.ToDateTime(dr["OffLAllotEndDate"]);//网下配售日期/网下配售截止日
                if (dr["NAPSBefore"] != null && dr["NAPSBefore"].ToString() != "")
                    model.NAPSBefore = Convert.ToDecimal(dr["NAPSBefore"]);//发行前每股净资产（元）
                if (dr["NAPSAfter"] != null && dr["NAPSAfter"].ToString() != "")
                    model.NAPSAfter = Convert.ToDecimal(dr["NAPSAfter"]);//发行后每股净资产（元）
                if (dr["SSTJRName"] != null)
                    model.SSTJRName = dr["SSTJRName"].ToString();//上市推荐人
                if (dr["ZCXSName"] != null)
                    model.ZCXSName = dr["ZCXSName"].ToString();//主承销商
                if (dr["FZCXSName"] != null)
                    model.FZCXSName = dr["FZCXSName"].ToString();//副主承销商
                if (dr["DistributeCommit"] != null)
                    model.DistributeCommit = dr["DistributeCommit"].ToString();//股利分配政策/分配承诺
                if (dr["ListPublDate"] != null && dr["ListPublDate"].ToString() != "")
                    model.ListPublDate = Convert.ToDateTime(dr["ListPublDate"]);//上市公告日期
                if (dr["OLRefundDate"] != null && dr["OLRefundDate"].ToString() != "")
                    model.OLRefundDate = Convert.ToDateTime(dr["OLRefundDate"]);//网上冻结资金返回日期
                if (dr["OffLRefundDate"] != null && dr["OffLRefundDate"].ToString() != "")
                    model.OffLRefundDate = Convert.ToDateTime(dr["OffLRefundDate"]);//网下冻结资金返回日期
                if (dr["LotRatePublDate"] != null && dr["LotRatePublDate"].ToString() != "")
                    model.LotRatePublDate = Convert.ToDateTime(dr["LotRatePublDate"]);//中签率公告日
                if (dr["OffLAllotStartDate"] != null && dr["OffLAllotStartDate"].ToString() != "")
                    model.OffLAllotStartDate = Convert.ToDateTime(dr["OffLAllotStartDate"]);//网下配售起始日
                if (dr["PricePublDate"] != null && dr["PricePublDate"].ToString() != "")
                    model.PricePublDate = Convert.ToDateTime(dr["PricePublDate"]);//网下配售起始日
                if (dr["PreInquiryEndDate"] != null && dr["PreInquiryEndDate"].ToString() != "")
                    model.PreInquiryEndDate = Convert.ToDateTime(dr["PreInquiryEndDate"]);//初步询价截止日期
                if (dr["PreInquiryStartDate"] != null && dr["PreInquiryStartDate"].ToString() != "")
                    model.PreInquiryStartDate = Convert.ToDateTime(dr["PreInquiryStartDate"]);//初步询价开始日期
                if (dr["OLRoadShowStartDate"] != null && dr["OLRoadShowStartDate"].ToString() != "")
                    model.OLRoadShowStartDate = Convert.ToDateTime(dr["OLRoadShowStartDate"]);//网上路演起始日
                if (dr["PromotionEndDate"] != null && dr["PromotionEndDate"].ToString() != "")
                    model.PromotionEndDate = Convert.ToDateTime(dr["PromotionEndDate"]);//现场推介截止日
                if (dr["PromotionStartDate"] != null && dr["PromotionStartDate"].ToString() != "")
                    model.PromotionStartDate = Convert.ToDateTime(dr["PromotionStartDate"]);//现场推介起始日
                if (dr["ProspectusPublDate"] != null && dr["ProspectusPublDate"].ToString() != "")
                    model.ProspectusPublDate = Convert.ToDateTime(dr["ProspectusPublDate"]);//招股公告日期

                list.Add(model);
            }

            return list;
        }
    }
}
